//
//  SDBaseData.m
//  SKinDiary
//
//  Created by pcyang on 16/6/26.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDBaseData.h"
#import "SDHttpRequestManagement.h"
#import "SDBaseData+Cache.h"
#import "SDServerSwitchManager.h"
#import "SDLoginManager.h"

@interface SDBaseData()
@property(nonatomic,strong)SDHTTPRequestOperation* request;
//@property(nonatomic,strong)VPJCEResponse* jceResponse;
@end

@implementation SDBaseData
- (id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if ( self )
    {
        self.lastUpdateTime = [aDecoder decodeObjectForKey:@"lastUpdateTime"];
        self.modelData = [aDecoder decodeObjectForKey:@"modelData"];
        
    }
    return self;
}

- (void) encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.lastUpdateTime forKey:@"lastUpdateTime"];
    [aCoder encodeObject:self.modelData forKey:@"modelData"];
    
}

#pragma mark ---

-(NSDictionary*)requestCookies
{
    SDLoginManager* loginMgr = [SDLoginManager sharedInstance];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:5];
    NSString* sessionId = [loginMgr sessionId];
    if (CHECK_VALID_STRING(sessionId)) {
        [dic setObject:[loginMgr sessionId] forKey:@"Token"];
    }
    
    return dic;
}

- (void) dealloc
{
    [self clearDelegatesAndCancel];
}

-(NSString*)getRequestUrl
{
    return nil;
}

- (void)resetWithResponseObj:(id)object
{
    
}

- (BOOL)isLoading
{
    return (self.request!=nil);
}

- (void)clear
{
    if(_request)
    {
        [_request clearDelegatesAndCancel];
        _request = nil;
    }
}

- (void)clearDelegatesAndCancel
{
    [self clear];
    _delegate = nil;
}

- (void)cancelRequest
{
    [self clear];
}

- (void)refreshData
{
    //    _loadPageType = VPLoadPageTypeRefresh;
    [self reloadDataWithCache:NO];
}

- (BOOL)hasLocalCacheFile{
    return [SDFile fileExist:[self cachePath]];
}

- (void)reloadDataWithCache:(BOOL)readCache
{
    _loadPageType = SDLoadPageTypeRefresh;
    
    if( ![SDFile fileExist:[self cachePath]] || !readCache )    {
        [self forceReloadData];
        return;
    }
    
    [self readFromFileWithCompletion:^{
        
        if( self.lastUpdateTime && [[NSDate date]timeIntervalSinceDate:self.lastUpdateTime] > [self cacheExpireTime] )
        {
            self.dataType = SDBaseDataTypeCache;
            [self refreshDataDidFinishWithError:nil withNextType:SDBaseDataTypeRefresh];
            ///无网不在请求
            if ([SDHttpRequestManagement sharedHttpRequestManagement].currentNetworkStatus != kNotReachable) {
                [self forceReloadData];
            }
        }
        else
        {
            [self refreshDataDidFinishWithError:nil withNextType:SDBaseDataTypeNone];
        }
    }];
}

-(void)pullDownLoadData
{
    _loadPageType = SDLoadPageTypePullDown;
    [self forceReloadData];
}

- (void)loadMoreData
{
    _loadPageType = SDLoadPageTypePullUp;
    
    [self forceReloadData];
}

+(id)modelFromResponseValues:(id)infos error:(NSError**)error
{
    return infos;
}

- (void)forceReloadData
{
    [self refreshDataWillStart];
    
    [self clear];
    
    Class selfClass = self.class;
    __weak typeof(self) weakSelf = self;
    NSString* url = [self getRequestUrl];

    self.request = [SDHttpRequestManagement startHttpRequestAndParsingResultWithURL:url
                                                                            priority:WYHttpRequestPriority_VeryHigh
                                                                      requestCookies:[self requestCookies]
                                                                   objectParserBlock:^id(id data, NSError **error)
                    {
                        id realData = [selfClass realJosnDataFromResponseData:data err:error];
                        return [selfClass modelFromResponseValues:realData error:error];
                    }
                                                                         completion:^(id data, NSError *error)
                    {
                        __strong SDBaseData* strongSelf = weakSelf;
                        if( !error )
                        {
                            strongSelf.dataType = SDBaseDataTypeRefresh;
                            strongSelf.lastUpdateTime = [NSDate date];
                            strongSelf.modelData = [strongSelf resetWithResponseModel:data];
//                            if ([strongSelf isNeedSaveModel] && strongSelf.modelData)
//                                [strongSelf saveToFile];
                        }
                        
                        if(nil==error)
                        {
                        }
                        else
                        {
                            NSInteger code = error.code;
                            if(SDHttpRequest_Errorcode_ResponseError==error.code && error.userInfo)
                                code = [[error.userInfo objectForKey:kSDHttpRequest_ResponseCode] integerValue];
                            
                        }
                        
                        strongSelf.request = nil;
                        [strongSelf refreshDataDidFinishWithError:error withNextType:SDBaseDataTypeNone];
                    }];
    
}

+(id)realJosnDataFromResponseData:(id)data err:(NSError**)error
{
    id realData = nil;
    
    if( error && *error == nil )
    {
        BOOL success = NO;
        NSString* code = nil;
        
        if( [data isKindOfClass:[NSDictionary class]] )
        {
            code = [data objectForKey:@"code"];
            
            if(code && [code isKindOfClass:[NSNumber class]])
                code = [NSString stringWithFormat:@"%d", [code intValue]];
            
            if(code)
                success = (code ? [code intValue]==0:NO);
            
            if( success )
            {
                realData = [data objectForKey:@"data"];
            }
        }
        
        if( !success )
        {
            NSString* errInfo = [data objectForKey:@"msg"];
            
            *error = [NSError errorWithDomain:SDHttpRequest_ErrorDomain
                                         code:SDHttpRequest_Errorcode_ResponseError
                                     userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
                                               getShowString(errInfo),kSDHttpRequest_ResponseInfo,
                                               getShowString(code), kSDHttpRequest_ResponseCode,nil]];
        }
    }
    
    return realData;
}

#pragma mark-
#pragma mark data callback
- (void)refreshDataWillStart
{
    if( self.delegate && [self.delegate respondsToSelector:@selector(dataWillStartLoad:)] )
        [self.delegate dataWillStartLoad:self];
}

- (void)refreshDataDidFinishWithError:(NSError*)error withNextType:(SDBaseDataType)nextDataType
{
    if( self.delegate && [self.delegate respondsToSelector:@selector(data:didFinishLoadWithError:nextDataType:)] )
        [self.delegate data:self didFinishLoadWithError:error nextDataType:nextDataType];
}
@end
